import Toast from '@vant/weapp/toast/toast';

var app = getApp()
// components/wrapItem/wrapItem.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    article:{
      type:Object,
      
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    star:0,
    openid:String
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 跳转到详情页
    goTodetail(){
      const star=this.data.star
      const {article} = this.properties
      this.triggerEvent("tapItem",{id:article.creation_id,star:star})
    },
    // 跳转到诗词对应的页面
    goToPoetryDetail(){
      const {article} = this.properties
      this.triggerEvent("tapItemPoetry",{id:article.poetryId})
    },
    // 点赞事件的处理函数
    async star(){
      // 未登录时跳转到登陆界面
      var is_login=app.globalData.is_login
      if(!is_login){return wx.showModal({
        title: '登录后使用',
        content: '是否跳转到登陆界面？',
        complete: (res) => {
          if (res.cancel) {
          }
          if (res.confirm) {
            wx.switchTab({
              url: '../../pages/my/my',
            })
          }
        }
      })}
      // 确认登录状态后更新点赞状态
      const star = this.data.star==0?1:0;
      const openid = this.data.openid
      const creation_id= this.data.article.creation_id
      // 记录当前点击事件是点赞还是取消点赞
      let flag=0
      // 文章原本的star数量
      let starCount = this.properties.article.starsCount;
      // 计算点击事件后点赞数
      if(star){
        // 点赞
        starCount = starCount+1
        flag=1
      }else{
        // 取消点赞
        flag=0
        starCount = starCount-1
      }
      // 更新文章表中star的值
      const res =await wx.$http.get('/write/community/creation/star/update',{
        flag:flag,
        starCount:starCount,
        creation_id:creation_id,
        user_openid:openid
      })
      this.setData({
        star,
        ['article.starsCount']:starCount
      })
    },
    // 查询文章是否被当前用户点赞
    async isStar(){
      // 当前文章的id
      const creation_id = this.data.article.creation_id
      // 当前用户的openid
      const openid = this.data.openid
      const res =  await wx.$http.get('/write/community/creation/star',{
        creation_id:creation_id,
        user_openid:openid
      })
      if(res.statusCode!=200)wx.$showMsg()
      const star = res.data
      this.setData({
        star:star
      })
    },
    // 更多
    handlemore(){
      console.log('more');
    }
  },
  // 生命周期函数
  lifetimes:{
  // 在attached周期函数中判断该文章是否被当前用户点赞
    attached(){
      if(app.globalData.is_login){
        this.setData({
          openid:app.globalData.userInfo.openid
        })
        // 调用判断方法
        this.isStar()
      }
      
    }
  }
  
  
})
